/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.acme.server;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author iiping
 */
public class Hexer {

	static final String HEXES = "0123456789ABCDEF";
	public static String getHex( byte [] raw ) {
		if ( raw == null ) {
			return null;
		}
	    final StringBuilder hex = new StringBuilder( 2 * raw.length );
	    for ( final byte b : raw ) {
	      hex.append(HEXES.charAt((b & 0xF0) >> 4))
	         .append(HEXES.charAt((b & 0x0F)));
	    }
	    return hex.toString();
	  }		
	
	public static String encodeMD5HexStr(String clearTxt)
		
	{
		try{
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(clearTxt.getBytes());
			return getHex(md.digest());
		}
		catch(NoSuchAlgorithmException e){
			//just switch back to clear text format
			return clearTxt;
		}
	}
	

	public static boolean testMD5HexStr(String clearTxt,String encodedMD5HexStr)
	
	{
		String encodedTestPassword = encodeMD5HexStr(clearTxt);
		return (encodedTestPassword.equals(encodedMD5HexStr));
	}

}
